package com.huan.study.sharding.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.huan.study.sharding.entity.CustomerOrder;
import com.huan.study.sharding.mappers.CustomerOrderItemMapper;
import com.huan.study.sharding.mappers.CustomerOrderMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 订单
 *
 * @author huan.fu 2021/5/25 - 下午1:40
 */
@RestController
public class CustomerOrderController {

    @Resource
    private CustomerOrderMapper customerOrderMapper;
    @Resource
    private CustomerOrderItemMapper customerOrderItemMapper;

    @GetMapping("/createOrder")
    public List<CustomerOrder> createOrder(@RequestParam(value = "size", defaultValue = "1") Integer size) {
        List<CustomerOrder> customerOrders = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            Snowflake snowflake = IdUtil.getSnowflake(1, 1);
            Long customerId = snowflake.nextId();
            long sallerId = snowflake.nextId();
            BigDecimal orderId = new BigDecimal(snowflake.nextId() + "" + customerId.toString().substring(customerId.toString().length() - 2));
            String productName = "商品-" + new Random().nextInt(100);
            customerOrderMapper.createOrder(orderId, customerId, sallerId, productName);
            customerOrderItemMapper.createOrderItem(orderId, customerId, "商品描述-" + new Random().nextInt(100));
            CustomerOrder order = new CustomerOrder();
            order.setCustomerId(customerId);
            order.setSallerId(sallerId);
            order.setOrderId(orderId);
            order.setProductName(productName);
            customerOrders.add(order);
        }
        return customerOrders;
    }

    @GetMapping("findOrder")
    public CustomerOrder findOrder(@RequestParam("orderId") BigDecimal orderId) {
        return customerOrderMapper.findOrder(orderId);
    }

    @GetMapping("findCustomerOrders")
    public List<CustomerOrder> findCustomerOrders(@RequestParam("customerId") Long customerId) {
        return customerOrderMapper.findCustomerOrders(customerId);
    }
}
